package com.xja.util;

import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileUtil {
    //重命名文件名
    public static String getFileName(String filename){
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate = format.format(date);
        return newDate+filename;
    }
    //重写路劲名
    public static String getFilePath(){
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        return format.format(date);
    }
    public static String getTransferToPath(MultipartFile file) throws FileNotFoundException {
        long size = file.getSize();
        if (size > 0) {
            //获取当前工程的绝对路径
            String realPath = ResourceUtils.getURL("classpath:").getPath()+"static/upload";
            /*获取文件上传的名称*/
            String filename = file.getOriginalFilename();
            //使用工具为文件名重命名
            String newFileName = FileUtil.getFileName(filename);
            //获取文件路径
            String datePath = FileUtil.getFilePath();
            //创建路径
            String filePath=realPath+"/"+datePath;
            //创建该路劲的文件对象
            File file1 = new File(filePath);
            if (!file1.exists()) {
                file1.mkdirs();
            }
            File file2 = new File(filePath + "/" + newFileName);
            try {
                file.transferTo(file2);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return datePath + "/" + newFileName;
        }
        return null;
    }

}
